<?php
/**
 * 订单管理
 * @author huangjian E-mail:870596179@qq.com
 * @version 创建时间：2015年11月10日 上午11:03:05 
 * 类说明
 */
class OrderAction extends BaseAction{
	
	/**
	 * @authority 浏览
	 */
	public function index(){
		$Order = M('Order');
		$this->assign("is_complain",$_REQUEST['is_complain']);
		$this->assign("has_refund",$_REQUEST['has_refund']);
		if(isset($_REQUEST['shop_id'])){
			$shop = M("Shop") ->where('flag = 1 and id = '.$_REQUEST['shop_id'])->find();
			if($shop['create_userid']==$this->uid){
				$this->assign("shop",$shop);
				$this->assign("shop_id",$_REQUEST['shop_id']);
			}else{
				$this->assign("shop_id",0);
			}

		}else{
			$this->assign("shop_id",0);
		}
		$school = M("School")->where('flag = 1')->select();
		$this->assign("school",$school);
		$count = $Order ->where('flag = 1 and status = 0')->count();
		$this->assign("count",$count);
		$this->display();
	}
	
	//列表
	public function getAllData(){
		$shop_list = M("Shop") ->where('flag = 1 and create_userid = '.$this->uid)->getField("id,name");
		$shop_id_arr = array_keys($shop_list);

		$Model = M($this->getActionName());
		$map = $this->loadSeachCondition();
		$map['a.flag'] = 1;
		$map['_string'] = 'a.shop_id=0 in ('.implode(",",$shop_id_arr).')';
		$where = $this->loadSeachConditionByA();
		$where['flag'] = 1;
		$map['_string'] = 'shop_id=0 in ('.implode(",",$shop_id_arr).')';
		$total = $Model->where($where)->count();// 查询满足要求的总记录数
		$page = json_decode($this->pageParam($total));
		if(!empty($page->sort)){
			$sort = 'a.'.$page->sort;
		}else{
			$sort = $page->sort;
		}
		$data = $Model->alias('a')->join('left join __USER__ as b on b.id = a.user_id left join __SHOP__ as c on a.shop_id=c.id')->field('a.id,a.code,a.user_id,a.register_tel,a.province,a.city,a.area,a.address,a.contact_name,a.contact_tel,a.mail_fee,a.mail_type,a.mail_time,a.total_price,a.real_price,a.pay_type,a.pay_time,a.pay_email,a.pay_code,a.status,a.give_time,a.done_time,a.return_apply_time,a.return_reason,a.return_time,from_unixtime(a.create_time) as create_time,a.update_time,a.flag,a.remark,b.parent_id,c.school_name,c.name as shop_name')->where($map)->limit($page->firstRow,$page->listRows)->order($sort)->select();
		$vo = $this->toJosnForGird($data,$page);
		echo json_encode($vo);
	}
	
	/**
	 * 组装条件
	 * @return multitype:multitype:string
	 */
	
	public function loadSeachConditionByA(){
		$map = array();
		if(!empty($_GET['register_tel'])){
			$map['register_tel'] = array("like","%".$_GET['register_tel']."%");
		}
		if(!empty($_GET['code'])){
			$map['code'] = array("like","%".$_GET['code']."%");
		}
		if($_GET['status'] != null){
			$map['status'] = $_GET['status'];
		}
		if(!empty($_GET['create_time_begin']) && !empty($_GET['create_time_end'])){
			$map['create_time'] = array(array("exp"," >= unix_timestamp('".$_GET['create_time_begin']."')"),array("exp"," <= unix_timestamp('".$_GET['create_time_end']." 23:59:59')"));
		}else if(!empty($_GET['create_time_begin'])){
			$map['create_time'] = array("exp"," >= unix_timestamp('".$_GET['create_time_begin']."')");
		}else if(!empty($_GET['create_time_end'])){
			$map['create_time'] = array("exp"," <= unix_timestamp('".$_GET['create_time_end']." 23:59:59')");
		}
		if(!empty($_GET['pay_type'])){
			$map['pay_type'] = $_GET['pay_type'];
		}
		if(!empty($_GET['mail_type'])){
			$map['mail_type'] = $_GET['mail_type'];
		}
		return $map;
	}
	public function loadSeachCondition(){
		$map = array();
		if(!empty($_GET['register_tel'])){
			$map['a.register_tel'] = array("like","%".$_GET['register_tel']."%");
		}
		if(!empty($_GET['code'])){
			$map['a.code'] = array("like","%".$_GET['code']."%");
		}
		if($_GET['status'] != null){
			$map['a.status'] = $_GET['status'];
		}
		if(!empty($_GET['create_time_begin']) && !empty($_GET['create_time_end'])){
			$map['a.create_time'] = array(array("exp"," >= unix_timestamp('".$_GET['create_time_begin']."')"),array("exp"," <= unix_timestamp('".$_GET['create_time_end']." 23:59:59')"));
		}else if(!empty($_GET['create_time_begin'])){
			$map['a.create_time'] = array("exp"," >= unix_timestamp('".$_GET['create_time_begin']."')");
		}else if(!empty($_GET['create_time_end'])){
			$map['a.create_time'] = array("exp"," <= unix_timestamp('".$_GET['create_time_end']." 23:59:59')");
		}
		if(!empty($_GET['pay_type'])){
			$map['a.pay_type'] = $_GET['pay_type'];
		}
		if(!empty($_GET['mail_type'])){
			$map['a.mail_type'] = $_GET['mail_type'];
		}
		if(!empty($_GET['shop_id'])){
			$map['a.shop_id'] = $_GET['shop_id'];
		}
		return $map;
	}
	
	/**
	 * @authority 详细
	 */
	public function detailView() {
		$Model = M($this->getActionName());
		$OrderDetailsModel = M('OrderDetails');
		$map['id'] = $_REQUEST['id'];
		$vo = $Model->where($map)->find();
		$orderDetailList = $OrderDetailsModel->where('order_code='.$vo['code'].' and flag=1')->select();
		$this->assign('orderDetailList',$orderDetailList);
		$this->assign('vo',$vo);
		$this->display();
	}
	
	/**
	 * 更改状态
	 */
	public function updateStatus() {
		$Model = M($this->getActionName());$User = M('User');$Fields = M("Fields");$UserDetails = M('UserDetails');
		if(false === $Model->create()) {
			$this->error($Model->getError());
		}
		$data = $Model->create();
		$info = $Model->where('id = '.$_POST['id'])->find();
		$data['status'] = $_REQUEST['status'];
		if($data['status'] == 3){
			$data['give_time'] = time();
			//推送
			$this->insertNotice($info['user_id'], "您的订单已发货！", $info['code']);
		}else if($data['status'] == 4){
			//分润
			$bl = (float) $Fields->where('field = "app_consume_return_rate" and flag = 1')->getField('value');//上级返现利率
			$price = sprintf("%.2f",$info['real_price'] * $bl);
			if(!empty($price)){
				$parentId = $User->where('id = '.$info['user_id'])->getField('parent_id');
				if(!empty($parentId)){
					$parentBalance = $User->where('id ='.$parentId)->getField("balance");
					$detailData['user_id'] = $parentId;
					$detailData['title'] = "消费返利";
					$detailData['type'] = 1;
					$detailData['price'] = $price;
					$detailData['last_price'] = $parentBalance;
					$detailData['from_user_id'] = $info['user_id'];
					$detailData['create_time'] = time();
					$result = $UserDetails->add($detailData);
					$result2 = $User->where('id = '.$parentId)->setInc('balance',$price);
				}
			}
			$data['done_time'] = time();
		}elseif($data['status'] == -2){
			$data['return_time'] = time();
		}elseif($data['status'] == -3){
			//推送
			$this->insertNotice($info['user_id'], "您的申请退款被拒绝！", $info['code']);
			$data['return_time'] = time();
		}
		// 更新数据
		if(false !== $Model->save($data)) {
			$this->ajaxReturn(1,L('ADMIN_EDIT_SUCCESS'),1);
		} else {
			$this->ajaxReturn(0,L('ADMIN_EDIT_ERROR'),0);
		}
	}
	
	
	/**
	 * 更新
	 */
	public function update() {
		$Model = M($this->getActionName());
		if(false === $Model->create()) {
			$this->error($Model->getError());
		}
		// 更新数据
		if(false !== $Model->save()) {
			$this->ajaxReturn(1,L('ADMIN_EDIT_SUCCESS'),1);
		} else {
			$this->ajaxReturn(0,L('ADMIN_EDIT_ERROR'),0);
		}
	}
	
	
	/**
	 * @authority 取消订单
	 */
	public function cancelOrder() {
		$Order = M('Order');
		$orderId = $_GET['orderId'];
		if(isset($orderId)){
			$info = $Order->where('id = '.$orderId)->find();
			if($info['status'] != 0){
				$this->error('订单状态错误，无法操作！');
			}
			$this->assign('vo',$info);
			if($info['pay_type'] == 1){//支付宝
				$this->display('alipayCancel');
			}elseif($info['pay_type'] == 2){
				$this->display('wxpayCancel');
			}elseif($info['pay_type'] == 3){
				$this->display('yueCancel');
			}
		}
	}
	
	/**
	 * 取消订单方法
	 * 微信
	 */
	public function cancelOrderWx(){
		$Order = M('Order');
		$orderId = $_POST['id'];
		if(!isset($orderId)){
			$this->ajaxReturn(0,'参数错误！',0);
		}
		$info = $Order->where('id = '.$orderId)->find();
		if($info['status'] != 0){
			$this->ajaxReturn(0,'订单状态错误，无法操作！',0);
		}
		import('COM.Core.WxpayAppUtils');
		$url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
		$WxpayUntils = new WxpayAppUtils();
		$postData["appid"] = C('WEIXIN_APPID');//公众账号ID
		$postData["mch_id"] = C('WEIXIN_MCHID');//商户号
		$postData["nonce_str"] = $WxpayUntils->createNoncestr();//随机字符串
		$postData['out_trade_no'] = $info['code'];
		$postData['transaction_id'] = $info['pay_code'];
		$postData['out_refund_no'] = $info['code'];
		$postData['total_fee'] = ($info['real_price'] + $info['mail_fee'])* 100;
		$postData['refund_fee'] = ($info['real_price'] + $info['mail_fee'])* 100;
		$postData['op_user_id'] = C('WEIXIN_MCHID');//操作员帐号, 默认为商户号
		$postData["sign"] = $WxpayUntils->getSign($postData);//签名
		$xml = $WxpayUntils->arrayToXml($postData);
		$result = $WxpayUntils->postXmlSSLCurl($xml,$url);
		$result = $WxpayUntils->xmlToArray($result);
		if($result['return_code'] == "SUCCESS"){
			//处理订单
			$data['flag'] = 1;
			$data['return_time'] = time();
			$data['status'] = -2;
			$Order->where('id = '.$orderId)->save($data);
			//推送
			$this->insertNotice($info['user_id'], "您的申请退款已成功！", $info['code']);
			$this->ajaxReturn(1,'退款成功！',1);
		}else{
			$this->ajaxReturn(0,'退款失败！',0);
		}
	}
	
	/**
	 * 取消订单
	 * 余额
	 */
	public function cancelOrderBalance(){
		$Order = M('Order');$UserDetails = M('UserDetails');$User = M('User');
		$Order->startTrans();
		$orderId = $_POST['id'];
		if(!isset($orderId)){
			$this->ajaxReturn(0,'参数错误！',0);
		}
		$info = $Order->where('id = '.$orderId)->find();
		if($info['status'] != 0){
			$this->ajaxReturn(0,'订单状态错误，无法操作！',0);
		}
		//金额返回给用余额
		$balance = $User->where('id ='.$info['user_id'])->getField("balance");
		$price = $info['real_price'] + $info['mail_fee'];
		$detailData['user_id'] = $info['user_id'];
		$detailData['title'] = "取消订单";
		$detailData['type'] = 1;
		$detailData['price'] = $info['real_price'] + $info['mail_fee'];
		$detailData['last_price'] = $balance;
		$detailData['create_time'] = time();
		$result1 = $UserDetails->add($detailData);
		$result2 = $User->where('id = '.$info['user_id'])->setInc('balance',$price);
		//处理订单
		$data['flag'] = 1;
		$data['return_time'] = time();
		$data['status'] = -2;
		$result3 = $Order->where('id = '.$orderId)->save($data);
		if($result1 && $result2 && $result3){
			//推送
			$this->insertNotice($info['user_id'], "您的申请退款已成功！", $info['code']);
			$Order->commit();
			$this->ajaxReturn(1,'退款成功！',1);
		}else{
			$Order->rollback();
			$this->ajaxReturn(0,'退款失败！',0);
		}
	}
	
	/**
	 * 新增消息
	 * 只新增个人订单消息
	 */
	private function insertNotice($userId,$message,$ambulance){
		$Notice = M('Notice');$User = M('User');
		$jpushId = $User->where('id = '.$userId)->getField('jpush_id');
		if(!empty($jpushId)){
			$data['type'] = 1;
			$data['user_id'] = $userId;
			$data['message'] = $message;
			$data['ambulance'] = $ambulance;
			$data['create_time'] = time();
			$Notice->add($data);
		}
		return true;
	}
	
	/**
	 * @authority 打印
	 */
	public function printView() {
		$Model = M($this->getActionName());$User = M('User');
		$OrderDetailsModel = M('OrderDetails');
		$map['id'] = $_REQUEST['orderId'];
		$vo = $Model->where($map)->find();
		$orderDetailList = $OrderDetailsModel->where('order_code='.$vo['code'].' and flag = 1')->select();
		$vo['parentId'] = (int) $User->where('id = '.$vo['user_id'])->getField('parent_id');
		$this->assign('orderDetailList',$orderDetailList);
		$count = 0;
		for($i=0;$i<count($orderDetailList);$i++){
			$count += $orderDetailList[$i]['num'];
		}
		$vo['list_count'] = $count;
		$this->assign('vo',$vo);
		$this->display();
	}
	
	/**
	 * @authority 打印快递单
	 */
	public function printmailView() {
		$Model = M($this->getActionName());$User = M('User');
		$map['id'] = $_REQUEST['orderId'];
		$vo = $Model->where($map)->find();
		$vo['parentId'] = (int) $User->where('id = '.$vo['user_id'])->getField('parent_id');
		$this->assign('vo',$vo);
		$this->display();
	}
	
		/**
	 * @authority 导出excel
	 */
	public function outExcel(){
		import('COM.Core.OutExcel');
		$Order = M('Order');
		$OutExcel = new OutExcel();
		$map = $this->loadSeachCondition();
		$map['flag'] = 1;
		$param['type'] = 'excel';//导出类型
		$param['exportFileName'] = date("Y-m-d",time()).'餐车订单';//标题
		$param['exportColumns']  = array(
				array('id','ID'),
				array('code','订单编号'),
				array('register_tel','用户名（手机号）'),
				array('real_price','实付款'),
				array('pay_type','支付方式'),
				array('mail_type','配送模式'),
				array('create_time','下单时间'),
				array('status','订单状态'),
				array('contact_name','收货人'),
				array('addressee','收货地址'),
		);
		$map = $this->loadSeachCondition();
		$map['a.flag'] = 1;
		if(!empty($page->sort)){
			$sort = 'a.'.$page->sort;
		}else{
			$sort = $page->sort;
		}
		$vo = $Order->alias('a')->join('left join __USER__ as b on b.id = a.user_id')->field('a.id,a.code,a.user_id,a.register_tel,a.province,a.city,a.area,a.address,a.contact_name,a.contact_tel,a.mail_fee,a.mail_type,a.mail_time,a.total_price,a.real_price,a.pay_type,a.pay_time,a.pay_email,a.pay_code,a.status,a.give_time,a.done_time,a.return_apply_time,a.return_reason,a.return_time,a.create_time,a.update_time,a.flag,a.remark,b.parent_id')->where($map)->limit($page->firstRow,$page->listRows)->order($sort)->select();
		//$vo = $Order->where($map)->select();
		for($i=0; $i<count($vo); $i++) {
			$vo[$i]['code'] = '`'.$vo[$i]['code'];
			$vo[$i]['create_time'] = date('Y/m/d',$vo[$i]['create_time']);
			$vo[$i]['real_price'] = ($vo[$i]['real_price'] + $vo[$i]['mail_fee']);
			switch ($vo[$i]['mail_type']){
				case 1 : $vo[$i]['mail_type'] = '校园模式';break;
				case 2 : $vo[$i]['mail_type'] = '快递模式';break;
				default: $vo[$i]['mail_type'] = '未知';
			}
			switch ($vo[$i]['pay_type']){
				case 1 : $vo[$i]['pay_type'] = '支付宝';break;
				case 2 : $vo[$i]['pay_type'] = '微信';break;
				case 3 : $vo[$i]['pay_type'] = '余额';break;
				default: $vo[$i]['pay_type'] = '未知';
			}

			switch ($vo[$i]['status']){
				case -3 : $vo[$i]['status'] = '拒绝退款';break;
				case -2 : $vo[$i]['status'] = '退款成功';break;
				case -1 : $vo[$i]['status'] = '失效';break;
				case 0 : $vo[$i]['status'] = '申请退款';break;
				case 1 : $vo[$i]['status'] = '未付款';break;
				case 2 : $vo[$i]['status'] = '已付款';break;
				case 3 : $vo[$i]['status'] = '配送中';break;
				case 4 : $vo[$i]['status'] = '完成';break;
				default: $vo[$i]['status'] = '未知';
			}
			$vo[$i]['addressee'] = $vo[$i]['province'].$vo[$i]['city'].$vo[$i]['area'].$vo[$i]['address'];
		}
		$param['exportDatas'] = $vo;
		$OutExcel->export($param);
	}

}